//
//  ShopManagerAlertView.m
//  rrbi
//
//  Created by mac book on 2018/12/20.
//

#import "ShopManagerAlertView.h"

///alertView  宽
#define AlertW 280/WIDTH_6S_SCALE
#define AlertH 180/HEIGHT_6S_SCALE
///各个栏目之间的距离
#define XLSpace 25/WIDTH_6S_SCALE
#define BtnSpace 20/WIDTH_6S_SCALE



@interface ShopManagerAlertView()<UITextFieldDelegate>

//弹窗
@property (nonatomic,strong) UIView *alertView;

@property (nonatomic,strong) UIImageView *redImageView;

//title
@property (nonatomic,strong) UILabel *titleLbl;

@property (nonatomic,strong) UILabel *priceLabel;

@property (nonatomic,strong) UILabel *priceShowLabel;

@property (nonatomic,strong) UILabel *messageLabel;

//确认按钮
@property (nonatomic,strong) UIButton *sureBtn;
//取消按钮
@property (nonatomic,strong) UIButton *cancleBtn;

@property (nonatomic, strong) UIButton *off_btn;

@property (nonatomic,strong) UITextField *priceTF;

@property (nonatomic,assign) ShopManagerAlert type;

@property (nonatomic,assign) BOOL isHaveDian;


@end


@implementation ShopManagerAlertView

- (instancetype)initAlertWithType:(ShopManagerAlert)type withText:(NSString *)text{
    if (self == [super init]) {
        
        self.type = type;
        self.frame = [UIScreen mainScreen].bounds;
        self.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
        
        self.alertView = [[UIView alloc] init];
        self.alertView.backgroundColor = [UIColor whiteColor];
        self.alertView.layer.cornerRadius = 10.0;
        [self addSubview:self.alertView];
        [self.alertView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.size.mas_equalTo(CGSizeMake(AlertW, AlertH));
        }];
        
        
        self.redImageView = [[UIImageView alloc]init ];
        self.redImageView.contentMode = UIViewContentModeScaleAspectFit;
        self.redImageView.image = [UIImage imageNamed:@"icon_lzh_people"];
        [self.alertView addSubview:self.redImageView];
        
        [self.redImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.alertView).offset(-35);
            make.left.equalTo(self.alertView).offset(-18);
            make.size.mas_equalTo(CGSizeMake(66, 80));
        }];
        
        
        self.off_btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.off_btn setImage:[UIImage imageNamed:@"icon_lzh_off"] forState:(UIControlStateNormal)];
        [self.alertView addSubview:self.off_btn];
        [self.off_btn addTarget:self action:@selector(singleTapAction) forControlEvents:(UIControlEventTouchUpInside)];
        [self.off_btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.right.equalTo(self.alertView);
            make.size.mas_equalTo(CGSizeMake(40, 40));
        }];
        
        
        self.titleLbl = [[UILabel alloc] init];
        self.titleLbl.textAlignment = NSTextAlignmentCenter;
        self.titleLbl.font = kFontNameSize(17);
        [self.alertView addSubview:self.titleLbl];
        [self.titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.alertView);
            make.height.mas_equalTo(40);
            make.left.right.equalTo(self.alertView);
            
        }];
        
        
        
        
        self.priceLabel = [[UILabel alloc] init];
        self.priceLabel.font = kFontNameSize(14);
        [self.alertView addSubview:self.priceLabel];
        [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleLbl.mas_bottom);
            make.height.mas_equalTo(35);
            make.left.equalTo(self.alertView).offset(20);
            make.width.mas_equalTo(70);

        }];
        
        
        
        
        self.priceShowLabel = [[UILabel alloc] init];
        self.priceShowLabel.font = kFontNameSize(14);
        [self.alertView addSubview:self.priceShowLabel];
        [self.priceShowLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self.priceLabel);
            make.left.equalTo(self.priceLabel.mas_right);
            make.right.equalTo(self.alertView).offset(-20);

        }];
        
        
        self.messageLabel = [[UILabel alloc] init];
        self.messageLabel.font = kFontNameSize(14);
        [self.alertView addSubview:self.messageLabel];
        [self.messageLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.priceLabel.mas_bottom);
            make.left.height.width.equalTo(self.priceLabel);

        }];
        
        
        _priceTF = [[UITextField alloc] init];
        _priceTF.borderStyle = UITextBorderStyleRoundedRect;
        [_priceTF setFont:kFontNameSize(14)];
        _priceTF.delegate = self;
//        _priceTF.textAlignment = NSTextAlignmentCenter;
        _priceTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self.alertView addSubview:_priceTF];
        [self.priceTF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.messageLabel);
            make.left.height.width.equalTo(self.priceShowLabel);
        }];
        
        
        
        self.sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.sureBtn.backgroundColor = getColor(greenBackColor);
        [self.sureBtn setTitle:@"确认" forState:UIControlStateNormal];
        self.sureBtn.titleLabel.font = kFontNameSize(14);
        [self.sureBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        self.sureBtn.adjustsImageWhenHighlighted = NO;
        self.sureBtn.layer.cornerRadius = 5.0;
        [self.alertView addSubview:self.sureBtn];
        
        
        
        
        //两个按钮
        self.cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        self.cancleBtn.backgroundColor =[UIColor lightGrayColor];
        //        [self.cancleBtn setTitleColor:  forState:UIControlStateNormal];
        self.cancleBtn.titleLabel.font = kFontNameSize(14);
        [self.cancleBtn addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
        self.cancleBtn.adjustsImageWhenHighlighted = NO;
        self.cancleBtn.layer.cornerRadius = 5.0;
        [self.alertView addSubview:self.cancleBtn];
        
        
        float btn_w = (AlertW- 60)/2;
        [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.alertView).offset(20);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(btn_w);
            make.bottom.equalTo(self.alertView.mas_bottom).mas_offset(-BtnSpace);
            
        }];
        
        [self.cancleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.width.equalTo(self.sureBtn);
            make.right.equalTo(self.alertView).offset(-20);
            
        }];
        
        self.sureBtn.tag = 1;
        self.cancleBtn.tag = 2;
        
        
        
        if (type == 1) {
            
            self.titleLbl.text = @"修改名称";
            self.priceLabel.text = @"商品名称：";
            self.messageLabel.text = @"修改名称：";
            _priceTF.placeholder = @"名称";
            self.priceShowLabel.text = text;
            self.priceTF.text = text;

        }else{
            self.titleLbl.text = @"修改价格";
            self.priceLabel.text = @"销售价：";
            self.messageLabel.text = @"修改价：";
            _priceTF.placeholder=@"金额";
            self.priceShowLabel.text = text;
            _priceTF.keyboardType = UIKeyboardTypeDecimalPad;

        }
       

        
    }
    
    return self;
}

#pragma mark - 弹出 -
- (void)showAlertView
{
    UIWindow *rootWindow = [UIApplication sharedApplication].keyWindow;
    [rootWindow addSubview:self];
    [self creatShowAnimation];
}

- (void)creatShowAnimation
{
    self.alertView.layer.position = self.center;
    self.alertView.transform = CGAffineTransformMakeScale(0.90, 0.90);
    [UIView animateWithDuration:0.25 delay:0 usingSpringWithDamping:0.8 initialSpringVelocity:1 options:UIViewAnimationOptionCurveLinear animations:^{
        self.alertView.transform = CGAffineTransformMakeScale(1.0, 1.0);
    } completion:^(BOOL finished) {
    }];
    
}

//点击事件
-(void)singleTapAction
{
    //具体的实现
    [self removeFromSuperview];
}


#pragma mark - 回调 -设置只有1  -- > 确定才回调
- (void)buttonEvent:(UIButton *)sender
{
    
    if (sender.tag == 1) {
        
        if (self.priceTF.text.length !=0 ) {
            if (self.resultIndex) {
                self.resultIndex(self.priceTF.text);
            }
            [self removeFromSuperview];
            
        }else{
              if (self.type == 2) {
                  [self makeToast:@"修改价格不能为空" duration:1 position:CSToastPositionCenter];

              }else{
                  [self makeToast:@"修改名称不能为空" duration:1 position:CSToastPositionCenter];
              }
        }
        
    }else{
        
        [self removeFromSuperview];
        
    }
    
}

//限制输入
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//
//    if (self.type == 2) {
//
//        if (string.length != 0 ){
//
//            NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
//            [str insertString:string atIndex:range.location];
//
//            if (str.length > 13 ){
//
//                return NO;
//            }
//
//            //如果输入的是“.”  判断之前已经有"."或者字符串为空
//            if ([string isEqualToString:@"."] && ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""])) {
//                return NO;
//            }
//
//            //限制输入（数字和.）
//            NSCharacterSet *cs= [[NSCharacterSet characterSetWithCharactersInString:@".0123456789"] invertedSet];
//            NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
//            BOOL basicTest = [string isEqualToString:filtered];
//            if (!basicTest) {
//                return NO;
//            }else{
//                return YES;
//            }
//
//        }
//
//    }
//    return YES;
//}


/**
 *  textField的代理方法，监听textField的文字改变
 *  textField.text是当前输入字符之前的textField中的text
 *
 *  @param textField textField
 *  @param range     当前光标的位置
 *  @param string    当前输入的字符
 *
 *  @return 是否允许改变
 */
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   
    /*
     * 不能输入.0-9以外的字符。
     * 设置输入框输入的内容格式
     * 只能有一个小数点
     * 小数点后最多能输入两位
     * 如果第一位是.则前面加上0.
     * 如果第一位是0则后面必须输入点，否则不能输入。
     */
    
    if (self.type == 2) {
        // 判断是否有小数点
        if ([textField.text containsString:@"."]) {
            self.isHaveDian = YES;
        }else{
            self.isHaveDian = NO;
        }
        
        if (string.length > 0) {
            
            NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
            [str insertString:string atIndex:range.location];
            if (str.length > 10 ){
                return NO;
            }
            
            //当前输入的字符
            unichar single = [string characterAtIndex:0];
            // 不能输入.0-9以外的字符
            if (!((single >= '0' && single <= '9') || single == '.'))
            {
                
                ShowViewMessage(@"您的输入格式不正确");
                return NO;
            }
            
            // 只能有一个小数点
            if (self.isHaveDian && single == '.') {
                ShowViewMessage(@"最多只能输入一个小数点");
                return NO;
            }
            
            // 如果第一位是.则前面加上0.
            if ((textField.text.length == 0) && (single == '.')) {
                textField.text = @"0";
            }
            
            // 如果第一位是0则后面必须输入点，否则不能输入。
            if ([textField.text hasPrefix:@"0"]) {
                if (textField.text.length > 1) {
                    NSString *secondStr = [textField.text substringWithRange:NSMakeRange(1, 1)];
                    if (![secondStr isEqualToString:@"."]) {
                        ShowViewMessage(@"第二个字符需要是小数点");
                        return NO;
                    }
                }else{
                    if (![string isEqualToString:@"."]) {
                        ShowViewMessage(@"第二个字符需要是小数点");
                        return NO;
                    }
                }
            }
            
            // 小数点后最多能输入两位
            if (self.isHaveDian) {
                NSRange ran = [textField.text rangeOfString:@"."];
                // 由于range.location是NSUInteger类型的，所以这里不能通过(range.location - ran.location)>2来判断
                if (range.location > ran.location) {
                    if ([textField.text pathExtension].length > 1) {
                        ShowViewMessage(@"小数点后最多有两位小数");
                        return NO;
                    }
                }
            }
            
        }
        
    }
    
    return YES;
}

@end
